#!/bin/bash
set -ex
ver=$1
git fetch upstream
git merge upstream/master 
sh generate-langpacks.sh $ver
sh process-official-tarball $ver
switch-ocs

date=$(date +"%Y%m%d")
sources_file="sources"

files=(
  "firefox-langpacks-${ver}-${date}.tar.xz"
  "firefox-${ver}.processed-source.tar.xz"
)

echo "🧹 删除 sources 中已有的 firefox- 开头的条目..."
grep -v 'firefox-' "$sources_file" > "${sources_file}.tmp"
mv "${sources_file}.tmp" "$sources_file"

for file in "${files[@]}"; do
  echo "🚀 上传：$file"

  output=$(upload-src firefox "$file")
  sha512_val=$(echo "$output" | grep -oE 'sha512/[0-9a-f]{128}' | cut -d/ -f2)
  if [[ -n "$sha512_val" ]]; then

    echo "➕ 写入新条目：$file"
    printf "SHA512 (%s) = %s\n" "$file" "$sha512_val" >> "$sources_file"
    rm -f "$file"
  else
    echo "❌ 未提取到 SHA512 值，请检查 upload-src 输出或文件名格式！"
    exit 1
  fi

  echo "---------------------------------------------"
done
echo "✅ sources 文件已更新完成。"
shortver="${ver%%esr}"
oldver=$(sed -n 's/^Version:[[:space:]]*//p' firefox.spec)
olddate=$(awk -F'-' '/^%global langpacks_date/ { split($NF, a, " "); print a[3] }' firefox.spec)
sed -i "s/^Version:[[:space:]]*$oldver/Version:        $shortver/" firefox.spec
sed -i "s|$olddate|$date|g" firefox.spec
sed -i 's/^Release: .*/Release:        0%{?dist}/' firefox.spec
gen-changelog firefox
